package com.qunar.tech.team12.shell.command;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.qunar.tech.team12.shell.exception.NoSuchCommandException;
import com.qunar.tech.team12.shell.io.Input;
import com.qunar.tech.team12.shell.io.Output;
import com.qunar.tech.team12.shell.io.impl.ParamInput;

import java.util.Collections;
import java.util.List;

/**
 * Created by mzy on 14-7-23.
 */
public class CommandParser {

    private static final int MAX_COMMANDS = 64;

    private static Splitter pipSplitter = Splitter.on("|").omitEmptyStrings().trimResults().limit(MAX_COMMANDS);
    private static Splitter spaceSplitter = Splitter.on(" ").omitEmptyStrings().trimResults().limit(MAX_COMMANDS);

    public static List<Command> parse(String line) {
        List<Command> commands = Lists.newArrayListWithCapacity(MAX_COMMANDS);
        List<String> list = pipSplitter.splitToList(line);

        for (String str : list) {
            List<String> cmdList = spaceSplitter.splitToList(str);
            List<String> options = Lists.newArrayListWithCapacity(MAX_COMMANDS);
            List<String> params = Lists.newArrayListWithCapacity(MAX_COMMANDS);

            try {
                Command command = CommandLoader.getCommand(cmdList.get(0));

                for (int i = 1; i < cmdList.size(); i++) {
                    String optionOrParam = cmdList.get(i);
                    if (optionOrParam.startsWith("-")) {
                        options.add(optionOrParam);
                    } else {
                        params.add(optionOrParam);
                    }
                }
                command.setOptions(options);
                command.setParams(params);
                command.setOutput(Output.PIPE);
                command.setIput(Input.PIPE);
                commands.add(command);
            } catch (NoSuchCommandException e) {
                return Collections.emptyList();
            }
        }
        if (!commands.isEmpty()) {
            commands.get(0).setIput(new ParamInput(commands.get(0).getParams()));
            commands.get(commands.size() - 1).setOutput(Output.CONSOLE);
        }
        return commands;
    }
}
